import EchartsWrap from '@/components/widgets/EchartsWrap';
import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
import { getProjectProgressStat } from '../../../../../services/kanbanServices';
// import svgSymbol from './svgPath';

var xAxisNames = [
  // '无锡交建集团',
  // '交通工程公司',
  // '无锡市航道工程有限公司',
  // '无锡市工业设备安装有限公司',
  // '华仁建设集团有限公司',
  // '无锡大城建设有限公司',
  // '园林绿化公司',
  // '无锡市正丰建设工程有限公司',
  // '无锡众合混凝土有限公司',
  // '无锡市众诚砼业有限公司',
  // '无锡市兴达桥梁工程有限公司',
  // '无锡市锡通博纳地筑路机械有限公司',
  // '包头市博达建设投资有限公司',
  // '业主单位',
];
var data1 = xAxisNames.map(e => Math.ceil(Math.random() * 500));
var data2 = xAxisNames.map(e => Math.ceil(Math.random() * 500));

const option = {
  backgroundColor: 'transparent',
  title: [
    {
      text: '总计',
      right: '380',
      top: '15',
      textStyle: {
        color: 'rgba(255,255,255,0.65)',
        fontSize: 15,
      },
    },
    {
      id: 'statistic',
      text: '',
      right: '340',
      top: '15',
      textStyle: {
        color: 'rgba(255,255,255,0.65)',
        fontSize: 14,
      },
    },
    {
      id: '右侧统计',
      text: '',
      textStyle: {
        rich: {
          a: {
            color: 'rgba(255,255,255,0.65)',
            fontSize: 14,
          },
          b: {
            color: '#2FB0FF',
            fontSize: 14,
          },
          c: {
            color: 'rgba(255,255,255,0.6)',
            fontSize: 14,
          },
        },
      },
      right: '40',
      top: '14',
    },
  ],
  legend: {
    data: ['实时产值', '计划产值', '计量产值'],
    orient: 'horizontal',
    icon: 'circle',
    itemWidth: 6,
    itemHeight: 6,
    textStyle: {
      color: 'rgba(255,255,255,0.65)',
    },
    show: true,
    left: 25,
    top: 15,
  },
  color: ['#3398DB'],
  tooltip: {
    trigger: 'axis',
    formatter: ' {b} <br/> {a0}: {c0} 亿元 <br/> {a1}: {c1} 亿元 <br/>  {a2}: {c2} 亿元 ',
    axisPointer: {
      // 坐标轴指示器，坐标轴触发有效
      type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
    },
  },
  grid: {
    left: '20',
    right: '20',
    bottom: '2',
    // bottom: '24',
    top: '55',
    containLabel: true,
  },
  xAxis: [
    {
      type: 'category',
      data: xAxisNames,
      // data: ['智行', '三公司', '武港院', '二公司', '广州分局'],
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        color: '#ACB7BC',
        rotate: 10,
        align: 'center',
        textStyle: {
          fontSize: 12,
        },
      },
      color: '#ACB7BC',
    },
  ],

  yAxis: [
    {
      type: 'value',
      axisLabel: {
        color: '#ACB7BC',
        textStyle: {
          fontSize: 12,
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#2D4754',
        },
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
    {
      type: 'value',
      axisLabel: {
        color: '#ACB7BC',
        textStyle: {
          fontSize: 12,
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#2D4754',
        },
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
  ],
  dataZoom: [
    {
      type: 'slider',
      show: true,
      start: 0,
      end: 50,
      height: 8,
      xAxisIndex: [0],
      bottom: 2,
      left: 44,
      handleIcon:
        'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
      handleSize: '100%',
      handleStyle: {
        color: '#d3dee5',
      },
      textStyle: {
        color: '#fff',
      },
      borderColor: '#90979c',
      labelFormatter: '',
    },
  ],
  series: [
    {
      name: '实时产值',
      type: 'bar',
      barWidth: '10',
      color: 'rgba(47, 255, 159, 1)',
      // data: data1,
      z: 10,
      label: {
        show: true,
        position: 'top',
        // offset: [0, 80],
        formatter: '{a}: {c} 亿元',
      },
    },
    {
      name: '计划产值',
      type: 'bar',
      barWidth: '10',
      color: 'rgba(47, 243, 255, 1)',
      data: data2,
    },
    {
      name: '计量产值',
      type: 'bar',
      barWidth: '10',
      color: 'rgba(47, 176, 255, 1)',
      // data: data2,
    },
  ],
};

const WorkingStatus = ({ curCompany, projList, companyList, kanLvl, dispatch }) => {
  const [curOption, setCurOption] = useState(option);
  const [statData, setStatData] = useState(null);

  function resetCurCompany() {
    dispatch({
      type: 'kanban/setCurCompany',
      payload: {
        curCompany: '',
      },
    });
  }

  function triggerOptionUpdate(projectsList = []) {
    const [
      projNameArr,
      accumulateValueArr,
      produceValueArr,
      calculateProduceValueArr,
      total,
      totalProducValue,
      totalAccumulateValue,
    ] = projectsList
      .sort((a, b) => {
        return b.totalActualProductValue - a.totalActualProductValue;
      })
      .reduce(
        (r, project) => {
          r[0].push(project.projectName);
          const FIXED_NUM = 3;
          const _totalActualProductValue = (project.totalActualProductValue / 10000).toFixed(
            FIXED_NUM,
          );
          const _totalPlanProductValue = (project.totalPlanProductValue / 10000).toFixed(FIXED_NUM);
          const _calculateProduceValue = (project.calculateProduceValue / 10000).toFixed(FIXED_NUM);

          r[1].push(+_totalActualProductValue);
          r[2].push(+_totalPlanProductValue);
          r[3].push(+_calculateProduceValue);

          // r[1].push(project.totalActualProductValue);
          // r[2].push(project.totalPlanProductValue);
          // r[3].push(project.calculateProduceValue);
          r[4] += 1;

          r[5] += +_totalActualProductValue;
          r[6] += +_totalPlanProductValue;
          // r[5] += +project.totalActualProductValue;
          // r[6] += +project.totalPlanProductValue;
          return r;
        },
        [[], [], [], [], 0, 0, 0],
      );

    let scrollBarEnd = 100;
    //  最多同时展示7个
    if (projNameArr.length > 7) {
      scrollBarEnd = Math.ceil((7 / projNameArr.length) * 100);
    }
    const newOption = JSON.parse(JSON.stringify(option));
    newOption.xAxis[0].data = projNameArr;

    newOption.series[0].data = accumulateValueArr;
    newOption.series[1].data = produceValueArr;
    newOption.series[2].data = calculateProduceValueArr;
    newOption.title[0].text = `总计${total}项`;
    newOption.title[2].text = `{a|总产值进度  } {b|${
      totalProducValue.toFixed(2)
      // Math.floor(totalProducValue * 100) / 1000000.toFixed(3)
    }} {c|亿元  }  {a|总计量进度  }  {b|${
      calculateProduceValueArr.reduce((r, e) => (r += +e), 0)
      // Math.floor(totalAccumulateValue * 100) / 1000000.toFixed(3)
    }} {c|亿元  }`;
    newOption.dataZoom[0].end = scrollBarEnd;
    setCurOption(newOption);
  }

  useEffect(() => {
    getProjectProgressStat().then(response => {
      const { data } = response;

      if (data && data.code === 200) {
        setStatData(data.data);
      }
    });
  }, []);
  
  useEffect(() => {
    if (statData) {
      triggerOptionUpdate(
        kanLvl === 'project'
          ? statData.resProjectInfoDto.projectInfoList
          : statData.resProjectDto.projectDetailList,
      );
    }
  }, [statData, kanLvl]);

  // useEffect(() => {
  //   if ((!curCompany && !projList.length) || (curCompany && !companyList.length)) return;
  //
  //   if (!curCompany) {
  //     // 全部
  //     triggerOptionUpdate(projList);
  //   } else {
  //     const _companyList = companyList.filter(e => e.companyName === curCompany)[0].projects;
  //     const _projList = [];
  //     projList.forEach(e => {
  //       if (
  //         _companyList.some(company => {
  //           return company.projectName === e.projectName;
  //         })
  //       ) {
  //         _projList.push(e);
  //       }
  //     });
  //     // 指定公司项目
  //     triggerOptionUpdate(_projList);
  //   }
  // }, [curCompany, projList, companyList]);
  return (
    <div className="chart-box" style={{ width: 'calc(100vw - 996px)', marginRight: 24 }}>
      <div className="chart-box-title">
        项目进度
        {curCompany && (
          <span style={{ cursor: 'pointer' }} onClick={resetCurCompany}>
            -{curCompany}
          </span>
        )}
      </div>
      <div className="chart-box-body">
        <EchartsWrap option={curOption} width={'100%'} opts={{ height: 240 }}></EchartsWrap>
      </div>
    </div>
  );
};

// export default WorkingStatus;
export default connect(({ kanban }) => {
  const { curCompany, projList, companyList, level } = kanban;
  return {
    projAndModelNumList: kanban.projAndModelNumList,
    curCompany,
    projList,
    companyList,
    kanLvl: level,
  };
})(WorkingStatus);
